package tw.com.softleader.gary.movie.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import tw.com.softleader.gary.movie.model.MovieModel;
import tw.com.softleader.gary.movie.service.MovieService;
import tw.com.softleader.gary.movie.service.impl.MovieServiceImpl;

public class MovieListServlet extends HttpServlet {
	
	public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		
		// getting movieService from ServletContext
		MovieService movieService =  (MovieService) this.getServletContext().getAttribute("movieService");
		if(movieService == null) {
			 movieService = new MovieServiceImpl();
			 this.getServletContext().setAttribute("movieService", movieService);
		}
		

		Collection<MovieModel> models = movieService.getAll();
		
		response.setContentType("text/html");
		
		PrintWriter out = response.getWriter();
		
		
		out.println("<a href='MovieAddServlet'>ADD</a>");
		
		out.println("<table border='1'>");
		out.println("<tr><th>FUNCTION</th><th>ID</th><th>NAME</th><th>LOCAL_NAME</th></tr>");
		for(MovieModel model:models) {
			out.println("<tr>");
			out.println("<td><a href='MovieEditServlet?id="+model.getId()+"'>EDIT</a> &nbsp;&nbsp; <a href='MovieDelServlet?id="+model.getId()+"'>DEL</a></td>");
			out.println("<td>"+model.getId()+"</td>");
			out.println("<td>"+model.getName()+"</td>");
			out.println("<td>"+model.getLocalName()+"</td>");
			out.println("</tr>");
		}
		
		out.println("</table>");
		
		
	}
	

}
